<?php  
$path = drupal_get_path('module', 'acts'); 
drupal_add_css($path . '/css/acts.css');
drupal_add_js($path . '/js/acts.js');

function actshome(){ 
global $base_url;
global $language;
	$url = $base_url . '/' . drupal_get_path('module', 'acts');
	$output = get_acts_header('dept');	
	$output .='<div class="result_inner"><div>';
	$output .= '<div id="depart_wise-wrapper">'. drupal_render(drupal_get_form('acts_search'));
	return $output;
}

function acts_search($form_state){
    $keyword = trim(arg(2));
	$options_first = department_dropdown_options();
	$form['department']= array(
		'#type' => 'select',
        '#title' => t('Department'),
        '#options' => $options_first,
        '#default_value' => $keyword ? $keyword : '',
		'#required' => TRUE,
	);       
    $form[ 'acts_submit' ] = array(
		'#title' => 'Submit', 
		'#type' => 'submit', 
		'#value' => 'Go', 
		'#name' => 'search',
		/*'#prefix' => '<div class="sea_go_but">',
		'#suffix' => '</div>',*/
		
	);
	if($keyword ==''){
		$ofirst = acts_deptlist();
	}
	else {
		$ofirst = acts_dept_datalist();
	}

	$form['field'] = array(
        '#type' => 'fieldset',
        '#title' => '',
        '#description' => $ofirst,
        '#tree' => TRUE,
    );
    return $form;
}
function acts_search_submit($form,&$form_state){
	global $base_url;	
	
	//print "form submit";  
	 
	// print "<pre>"; print_r($form_state); print "</pre>";
	 //drupal_set_message(t('The form has been submitted.')); die;
	 
	 	if ($form_state[clicked_button]['#name'] == 'search') {		
			$str = $form_state[values][department];		
		}
		$form_state['redirect'] = 'acts/dept/'.$str; 
    return;
}
function acts_dept_data(){
global $base_url;
global $language; 
$keyword = trim(arg(2));
	$url = $base_url . '/' . drupal_get_path('module', 'acts');
	$output = actshome();
return $output;
}
function acts_dept_datalist(){
global $base_url;
global $language; 
$keyword = trim(arg(2));
	my_db_change(1);
	$query = new EntityFieldQuery();
	$query->entityCondition('entity_type', 'node')
	  ->entityCondition('bundle', 'actform')   
	  ->propertyCondition('status',1)
	  ->fieldCondition('field_act_dpt','value',$keyword,'=')
	  ->propertyCondition('language', array($GLOBALS['language']->language, ''), 'IN')
	   ->fieldOrderBy('field_act_dpt','value','ASC')
	  ->fieldOrderBy('field_act_year','value','DESC');
	 // ->propertyCondition('language', $language->language, '=');
	  
	$result = $query->execute();
	
	
	$nid = current($result['node']);
	
	if (isset($result['node'])) {
	    $news_items_nids = array_keys($result['node']);
	  
		//$items = entity_load('node', $news_items_nids);
	}
	my_db_change(0);
	//print "<pre>";print_r($items);print "</pre>";
	$output .= theme('acts_profile_theme',array('items' => $news_items_nids));
	$output .='</div>';
return $output;
}
function get_acts_header($css){
	global $base_url;
/*	 if($css=='cate') { $cate_cls= "view_head_sel"; }else {$cate_cls='view_head_nonsel'; }*/
     if($css=='dept') { $dept_cls= "view_head_sel"; }else {$dept_cls='view_head_nonsel'; }
     if($css=='find') { $find_cls= "view_head_sel"; }else {$find_cls='view_head_nonsel'; }
	 if($css=='atoz') { $atoz_cls= "view_head_sel"; }else {$atoz_cls='view_head_nonsel'; }
	  
	   
	global $language;
	if($language->language=='ta'){
		$css='acts_ta';
		$lang='/ta'; 
		
	}
	else{
		$css='acts';
		$lang='';
	}
	
	$html = "<div class='view-header' id='viewmod_$css'>
				<div class='inner_tab_content'>
				<div class='inner_li'><a class='$dept_cls' href='$base_url$lang/acts/deptname'>".t('Department wise')."</a></div>					
				<div class='inner_li'><a class='$find_cls' href='$base_url$lang/acts/search'>".t('Search')."</a></div>
				<div class='inner_li'><a class='$atoz_cls' href='$base_url$lang/acts/atoz'>".t('A to Z')."</a></div>
				<div class='clr'></div></div></div>";
	return $html;
}
function department_dropdown_options(){
	my_db_change(1);
	$sql = db_query(" Select dept_name,dep_id from depart_mst order by dep_id"); 
	$departemtn[] = 'ALL';
	foreach ($sql as $dept) {
	//print_r($dept);
            $departemtn[] = $dept->dept_name ;
   }
	return $departemtn;
}
function acts_deptlist(){ 
global $base_url;
global $language;
	my_db_change(1);
	$query = new EntityFieldQuery();
	$query->entityCondition('entity_type', 'node')
	  ->entityCondition('bundle', 'actform')   
	  ->propertyCondition('status',1)
	  ->propertyCondition('language', array($GLOBALS['language']->language, ''), 'IN')
	  ->fieldOrderBy('field_act_dpt','value','ASC')
	   ->fieldOrderBy('field_act_year','value','DESC');
	 // ->propertyCondition('language', $language->language, '=');
	  
	$result = $query->execute();
	
	
	$nid = current($result['node']);
	
	if (isset($result['node'])) {
	    $news_items_nids = array_keys($result['node']); 
	  
		//$items = entity_load('node', $news_items_nids);
	}
	my_db_change(0);
	print "<pre>";print_r($news_items);print "</pre>";
	//$output .= theme('acts_profile_theme',array('items' => $items,'nid'=>$nid));
	$output .='</div>';
	$output .= theme('acts_profile_theme',array('items' => $news_items_nids,'nid'=>$nid));
	//$output .='</div>';
	
return $output;
}
function actsalpha(){
global $base_url;
global $language;
$alp = arg(2);
	$url = $base_url . '/' . drupal_get_path('module', 'acts');
	$output = get_acts_header('atoz');	
	$output .= "</div>". AtoZ_letters($alp) . "</div>";
	$output .='<div class="result_inner"><div>';
	$val= strtoupper($alp);	
	 
	 my_db_change(1);
		if($val != 'ALL'){
 
		$query = new EntityFieldQuery();
		$query->entityCondition('entity_type', 'node')
			  ->entityCondition('bundle', 'actform')   
			  ->propertyCondition('status',1)
			  ->propertyCondition('title',$val.'%','LIKE')
			  ->propertyCondition('language', array($GLOBALS['language']->language, ''), 'IN')
			// ->propertyOrderBy('title','ASC')
			 //  ->fieldOrderBy('field_act_dpt','value','ASC')
	 		  ->fieldOrderBy('field_act_year','value','DESC');
		 }
		 else {
 
			$query = new EntityFieldQuery();
			$query->entityCondition('entity_type', 'node')
			  ->entityCondition('bundle', 'actform')   
			  ->propertyCondition('status',1)
			  ->propertyCondition('language', array($GLOBALS['language']->language, ''), 'IN')
			  //->propertyOrderBy('title','ASC')
			  //->fieldOrderBy('field_act_dpt','value','ASC')
	  		  ->fieldOrderBy('field_act_year','value','DESC');
		 }
		$result = $query->execute();
	
	
	$nid = current($result['node']);
	
	if (isset($result['node'])) {
	  $news_items_nids = array_keys($result['node']);
	}
	//print "<pre>";print_r($items);print "</pre>";
	my_db_change(0);
	$output .= theme('acts_atoz_theme',array('items' => $news_items_nids,'nid'=>$nid));
	//$output .= theme('pager');
return $output;
}
function AtoZ_letters($alp){
	global $base_url;
		//print_r( strtolower($alpha ));
	for($i =65; $i < 91; $i++){
			$class = "";
	
// strtolower($val );
		if(chr($i) == $alp){
			$class = " view_head_sel";
		}
		else
		{
			$class = " ";
		}
		//$linkOp .= l($val,'acts/atoz/'.$val,array('attributes'=>array('class'=>$class)))."&nbsp;&nbsp;";
		 $linkOp .= '<a class = "myclass' . $class . '"  href = "' .$base_url.'/acts/atoz/'. chr($i) .'" >' . chr($i) . '</a>';
	}
	$class = "";
	if($alp == 'All'){
		$class = " view_head_sel";
	}
	$linkOp .= '<a class = "myclass' . $class . '" href = "' .$base_url.'/acts/atoz/All" title = "All" id = "All"> All </a>';
	$StrOp = "<div class='result_inner_atoz'>";
	$StrEnd = "</div>";
	$Grey = "<div class='grey_bord_line'></div>";//$linkOp .="<br /><br />";
	return $StrOp . $linkOp . $Grey . $StrEnd;
}
function acts_search_form(){
global $base_url;
global $language;
	$url = $base_url . '/' . drupal_get_path('module', 'acts');
	$output = get_acts_header('find');	
	$output .= drupal_render(drupal_get_form('acts_search_t'));
	$output .= '</div>';
return $output;
}
function acts_search_t($form_state){
$keyword = trim(arg(2));
	/*    $form['field'] = array(
			'#type' => 'fieldset',
			'#title' => '',
			'#description' => $output,
			'#tree' => TRUE,
        );	*/
		$form[ 'label' ]=array(
			'#prefix'=>'<div class="result_inner">'
		);
		$form[ 'hidden_content' ] = array(
			'#type' => 'hidden',
			'#default_value' => 'acts',
		 );
		$form[ 'cont_search' ] = array(
			'#title' => 'Search', 
			'#type' => 'textfield',
			'#default_value' => $keyword ? $keyword : '',
	    	'#required' => true, 
			'#size' => 35,
		 	//'#default_value' => get_search_session('cont_search')
		 );
		$form['search_subm'] = array(
			'#title' => 'Submit', 
			'#type' => 'submit', 
			'#value' => t('Go'), 
			'#name' => 'Go',
			'#prefix' => '<div class="sea_go_but1">',
            '#suffix' => '</div>',
		);
		/*$form['rad_act'] = array(
			'#type' => 'radio',
			'#options' => array(
				'act_title'=>t('Act Title'),
				'act_number'=>t('Act Number')
			 ),      
			 '#attributes' => array( 
				 'onclick' => 'ActClearSelectBox(this)'),
				// '#default_value' => get_search_session('rad_act')
		);	*/
		$form['rad_act'] = array(
		  '#type' => 'radios',		 
		     act_title => array(
				'#type' => 'radio',
				'#name' => 'rad_act',
				'#title' => t('Act Title'),
				'#return_value' => 0,
				//'#default_value' => variable_get('cont_search', 1),
				'#attributes' => array( 
					 'onclick' => 'ActClearSelectBox(this)'),
				'#default_value' => get_search_session('rad_act')
			  ),
			  act_number => array(
				'#type' => 'radio',
				'#name' => 'rad_act',
				'#title' => t('Act Number'),
				'#return_value' => 1,
				//'#default_value' => variable_get('cont_search', 1),
				'#attributes' => array( 
					 'onclick' => 'ActClearSelectBox(this)'),
				'#default_value' => get_search_session('rad_act')
			  ),
			);	
	    $form['act_search_year'] = array(
			'#type' => 'select',
			'#name' => 'act_search_year',
			'#options' =>array(
				''=>'Select Year',
				'1640-1660'=>'1640-1660',
				 '1680-1700'=>'1680-1700',
				 '1720-1740'=>'1720-1740',
				 '1760-1780'=>'1760-1780', 
				 '1800-1820'=>'1800-1820',
				 '1840-1860'=>'1840-1860',
				 '1880-1900'=>'1880-1900',
				 '1920-1940'=>'1920-1940',
				 '1960-1980'=>'1960-1980',
				 '2000-2010'=>'2000-2010'
			 ),'#attributes' => array(
				// 'style'=>'width:19%;',
				 'onclick' =>'ActClearRadioButton(this)',
			 ),
			 '#default_value' => get_search_session('act_search_year')
		);
		return $form;
}
function acts_search_t_submit($form, &$form_state){
		if ($form_state[clicked_button]['#name'] == 'Go')
		    {
				$cont_search = $form_state[values][cont_search];
				$rad_act= $form_state[values][rad_act];
				$act_search_year= $form_state[values][act_search_year];
				set_search_session('cont_search' , $cont_search);
				set_search_session('rad_act' , $rad_act);
				set_search_session('act_search_year' , $act_search_year);
				$form_state['redirect'] = 'acts/search/'.$cont_search.'/'.$rad_act.'/'.$act_search_year;
			}		
		return;
}

function acts_search_result_form() {
global $base_url;
global $language;
	$url = $base_url . '/' . drupal_get_path('module', 'acts');
	$output = get_acts_header('find');	
	$output .= drupal_render(drupal_get_form('acts_search_t'));
	$actitle = arg(2);
	$actno = arg(3);
	$year = arg(4);
	$ser_string = array();
    $keyword = trim(strtolower(get_search_session('cont_search')));
	$keyword=pg_escape_string($keyword);
	$keyword = preg_replace('/[\p{Z}\s]{2,}/u', ' ', $keyword);
	$len = drupal_strlen($keyword);
	$keyword1 =$keyword;
	if(!empty($keyword1)){
		$position[0]=strpos($keyword1,'"');
 		if($position[0] != "");{
 		 	$position[1]=strpos($keyword1,'"',$position[0]+1);
 		}
   }
   if(!empty($position[1])) {
		$k=0;
		for($i=0;$i<=$len;$i++){	
			$position[0]=strpos($keyword1,'"');
			if(strlen($keyword1) !=0){
				if($position[0] !=0 && $position[0] !="")
					$str_not_quote[$k++] =substr($keyword1,0,$position[0]);
				if($position[0] ==false)
					$str_not_quote[$k++] =substr($keyword1,0,strlen($keyword1));
			}	
	 $position[1]=strpos($keyword1,'"',$position[0]+1);	
	 if(empty($position[1])){
		 break;
	 }
	 $sub_string_len = $position[1] - $position[0]-1;	 
	 $ser_string[$i] = substr($keyword1,$position[0]+1, $sub_string_len);	
	 $part_string= substr($keyword1,$position[1]+1, $len);	
	 $keyword1 =trim($part_string);
	 if(empty($keyword1)){
		break;
	}
	}
	}
	$ser_string = array_filter_customize($ser_string);
function search_keyword($colum_name, $ser_string, $str_not_quote){
	$i=0;
	foreach($ser_string as $key => $value){
		if($i==0)
		$ser_keywords .= $colum_name." like '%%".$value."%' ";
		else
		$ser_keywords .= "and ".$colum_name." like '%%".$value."%' ";
		$i++;		
	}
	$i=0;
	foreach($str_not_quote as $key => $value){	
		if($i==0)
		$ser_keywords_not_quote .= $colum_name." like '%%".$value."%' ";
		else
		$ser_keywords_not_quote .= "or ".$colum_name." like '%%".$value."%' ";
		$i++;	
	}
	return "((".$ser_keywords.") or (".$ser_keywords_not_quote."))";
}
    $act_rad= trim(get_search_session('rad_act'));
	$act_year=trim(get_search_session('act_search_year'));
	$keyword = strtolower($keyword);
	my_db_change(1);
	$sql_search_clause="LOWER(replace(n.title, ' ', ' ')) LIKE '%%" . trim($keyword) . "%'";
	$sql_search_clause_num= "  LOWER(c.field_act_number_value) LIKE '%%$keyword%'";
	$sql_search_clause_year="LOWER(n.title) LIKE '%%$keyword%' OR LOWER(c.field_act_keyword_value) LIKE '%%$keyword%' OR LOWER(c.field_act_title_value) LIKE '%%$keyword%'                                OR LOWER(c.field_act_objectives_value) LIKE '%%$keyword%' OR LOWER(c.field_act_details_value) LIKE '%%$keyword%' OR LOWER(c.field_act_extent_value)                                    LIKE '%%$keyword%'";
    if(!empty($ser_string)) {
        $sql_search_clause = search_keyword(LOWER(replace(n.title, ' ', ' ')), $ser_string, $str_not_quote);
	}	
	if(!empty($ser_string)) {
         $sql_search_clause_num = search_keyword('LOWER(c.field_act_number_value)', $ser_string, $str_not_quote);
	}
    if(!empty($ser_string)) {
		$sql_search_clause_year = search_keyword('LOWER(n.title)', $ser_string, $str_not_quote);
		$sql_search_clause_year .= "or ";
		$sql_search_clause_year = search_keyword('LOWER(c.field_act_title_value)', $ser_string, $str_not_quote);
		$sql_search_clause_year .= "or ";
		$sql_search_clause_year .= search_keyword('LOWER(c.field_act_keyword_value)', $ser_string, $str_not_quote);
		$sql_search_clause_year .= "or ";
		$sql_search_clause_year .= search_keyword('LOWER(c.field_act_objectives_value)', $ser_string, $str_not_quote);
		$sql_search_clause_year .= "or ";
		$sql_search_clause_year .= search_keyword('LOWER(c.field_act_details_value)', $ser_string, $str_not_quote);
		$sql_search_clause_year .= "or ";
		$sql_search_clause_year .= search_keyword('LOWER(c.field_act_extent_value)', $ser_string, $str_not_quote);
       // $dept_search_clause = search_keyword('LOWER(dept_name)', $ser_string, $str_not_quote);
    }
	if(empty($keyword)){
		$result=$keyword;
    }else {
		 if($act_rad !='') { 
		 	if($act_rad=='0') {
		 		
			$query = new EntityFieldQuery();
			$query->entityCondition('entity_type', 'node')
			 	->entityCondition('bundle', 'actform')
             	->fieldCondition('field_act_title','value','%'.trim($keyword).'%','LIKE')		
			// ->fieldCondition('field_act_year','value','%%'.trim($keyword).'%','LIKE')	 
			  	->propertyCondition('status',1)
			   	->fieldOrderBy('field_act_year','value','DESC');			  
			$result = $query->execute();			
			$count = $query->count()->execute();
			$nid = current($result['node']);			
			if (isset($result['node'])) {
				  $news_items_nids = array_keys($result['node']); 
				  
				  $items = entity_load('node', $news_items_nids);
				}	//print "<pre>";print_r($items);print "</pre>";
			}
		}
		if($act_rad=='1'){
		$query = new EntityFieldQuery();
			$query->entityCondition('entity_type', 'node')
			  ->entityCondition('bundle', 'actform')	
			  //->propertyCondition('title','%%'.trim($keyword).'%','LIKE')	
             //->fieldCondition('field_act_title','value','%%'.trim($keyword).'%','LIKE')		
			  ->fieldCondition('field_act_year','value','%%'.trim($keyword).'%','LIKE')	 
			  ->propertyCondition('status',1)
			   ->fieldOrderBy('field_act_year','value','DESC');			  
				$result = $query->execute();			
				$count = $query->count()->execute();
				$nid = current($result['node']);			
				if (isset($result['node'])) {
				  $news_items_nids = array_keys($result['node']); 
				  
				  $items = entity_load('node', $news_items_nids);
				}	//print "<pre>";print_r($items);print "</pre>";
		}
		 elseif($act_year!=''){
		   $split_year = split('-',$act_year); 
		   $year1=$split_year['0'];
		   $year2=$split_year['1'];
		   $query = new EntityFieldQuery();
			$query->entityCondition('entity_type', 'node')
			  ->entityCondition('bundle', 'actform')	
			 // ->propertyCondition('title','%%'.trim($keyword).'%','LIKE')	
				//->fieldCondition('field_act_title','value','%%'.trim($keyword).'%','LIKE')		
			  ->fieldCondition('field_act_title','value','%%'.trim($keyword).'%','LIKE')	
			  ->fieldCondition('field_act_year','value',array($year1,$year2),BETWEEN)
			  ->fieldOrderBy('field_act_year','value','DESC') 
			  ->propertyCondition('status',1);			  
				$result = $query->execute();			
				$count = $query->count()->execute();
				$nid = current($result['node']);			
				if (isset($result['node'])) {
				  $news_items_nids = array_keys($result['node']);
				  $items = entity_load('node', $news_items_nids);
				}	//print "<pre>";print_r($items);print "</pre>";
				
		}
	}
	my_db_change(0);
	$output .= '<div class="result_search">';
	if($count != '0') {
		$output .='<div class="clr"><div class="record_found">'.$count.' Records Found</div></div>';
	}
	$output .= theme('acts_search_theme',array('items' => $news_items_nids));
	$output .= '</div></div>';
	
return $output;

}